package com.wnxy.admin.task;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wnxy.admin.dto.ChargingStationDto;
import com.wnxy.admin.entity.ChargingStation;
import com.wnxy.admin.mapper.ChargingStationMapper;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 定时更新充电站到es 定时器类
 * </p>
 *
 * @author nhj
 */

@Component
public class UpDateChargingStation {

    private final ChargingStationMapper chargingStationMapper;
    private final ElasticsearchRestTemplate elasticsearchRestTemplate;

    public UpDateChargingStation(ChargingStationMapper chargingStationMapper, ElasticsearchRestTemplate elasticsearchRestTemplate) {
        this.chargingStationMapper = chargingStationMapper;
        this.elasticsearchRestTemplate = elasticsearchRestTemplate;
    }
    @Transactional
    @Scheduled(fixedRate = 120000)//2分钟
    public void upDateCharging(){

        List<ChargingStation> chargingStations =
                chargingStationMapper.selectList(Wrappers.lambdaQuery(ChargingStation.class));

        List<ChargingStationDto> collect = chargingStations.stream()
                .filter(c -> c.getCoordinate() != null && c.getCoordinate() != "")
                .map(c -> {
                    ChargingStationDto dto = new ChargingStationDto();
                    BeanUtil.copyProperties(c, dto);
                    dto.setChargingStationState(c.getChargingStationState() == 1 ? "营业中" : "歇业");
                    return dto;
                })
                .collect(Collectors.toList());

        //将数据加到es中
        elasticsearchRestTemplate.save(collect);

    }
}
